﻿using System.Linq;
using System.Web.Mvc;
using GuildStock.Models;
using GuildStock.Services;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System;
using GuildStock.Services.Blizzard;
using GuildStock.Services.JsonToDynamic;
using System.Globalization;

namespace GuildStock.Controllers
{
    /// <summary>
    /// Home page controller
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// Main page
        /// </summary>
        public ActionResult Index(string r)
        {
          ViewData["GuildsInfo"] = Guild.GetRankedList(r, 30);
          ViewData["RealmFilter"] = r;

          return View();
        }

        [HttpPost]
        public ActionResult AddGuild(string guild, string realm)
        {
          new GuildProcessor().LoadGuildAsync(guild, realm);
          return View();
        }

        public ActionResult UpdateGuilds()
        {
          RealmProcessor.UpdateRealmsAsync();
          return RedirectToAction("Index");
        }
        
        public JsonResult GetJsonRealmList(string term)
        {
          var realms = new GuildStockDataDataContext().Realms.Select(r => ZonesExtensions.FullName(r.Name, r.Zone)).ToList();
          
          var matches = realms.Where(x => x.StartsWith(term, StringComparison.CurrentCultureIgnoreCase)).ToList();
          var matchesCount = matches.Count();

          if (matchesCount < 10)
          {
            var anyMatches = realms
              .Where(r => !matches.Any(s => string.CompareOrdinal(s, r) == 0))
              .Where(x => x.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
              .Take(10 - matchesCount);

            var tmp_matches = matches.Concat(anyMatches).ToList();
            matches = tmp_matches;
          }

          return Json(matches, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GuildDetails(string g, string r)
        {
          return View();
        }
    }
}
